﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Runtime.InteropServices;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Drawing.Drawing2D;
using System.Threading;
using Sunny.UI;
using System.Threading.Tasks;
using CoreShop.Library;
using RestSharp;
using CoreShop.Model;
using CoreShop.Services;
using MySqlX.XDevAPI.Common;
using Sunny.UI.Win32;
using SqlSugar;
using System.Diagnostics;
using CoreShop.App.Units.Interface;
using Loading;

namespace CoreShop.App
{
    /// <summary>
    /// 六小象AI
    /// </summary>
    public partial class frmSetupLxxAi : UIForm
    {
        OpaqueCommand cmd = new OpaqueCommand();
        public static Hashtable config = null;
        string url = $"{GlobalConstVars.AIData.LxxAiUrl}:{GlobalConstVars.AIData.LxxAiPort}";
        public frmSetupLxxAi()
        {
            InitializeComponent();
        }

        public void SetLogInfo(string msg)
        {
            this.rtb_log.Invoke(new Action(() =>
            {
                if (rtb_log.Text.Length > 30000) rtb_log.Clear();
                //this.richTextBox1.Text = msg + richTextBox1.Text;
                this.rtb_log.AppendText(msg);
                this.rtb_log.HideSelection = false;
            }));
        }

        private void Lxx_SetStart()
        {
            string content = "";
            try
            {
                //int ret = start_service("c:\\", "Unknown");
                //int ret = start_service(Application.StartupPath, "Unknown");
                // 连接AI
                SetLogInfo(url + "/rpc/get/version" + "\r\n");
                var request = WebRequest.Create(url + "/rpc/get/version");
                request.Method = "POST";
                var response = (HttpWebResponse)request.GetResponse();
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    content = sr.ReadToEnd();
                }
                SetLogInfo("content:" + content + "\r\n");
                var status = JObject.Parse(content);
                if ((status.GetValue("code").ToString() == "1") && (status.GetValue("msg").ToString() == "success"))
                {
                    this.Invoke(new Action(() =>
                    {
                        this.label6.Text = "已连接";
                    }));
                }           
            }
            catch (Exception ex)
            {
                UIMessageTip.Show(ex.Message + " content:" + content);
            }
        }

        /// <summary>
        /// 检查激活状态
        /// </summary>
        private void Lxx_GetRegister()
        {
            try
            {
                var lxxDeviceInfo = GlobalConstVars.lxxAIBusiness.GetDeviceInfo();

                if (lxxDeviceInfo == null) return;

                if (lxxDeviceInfo.code == 1)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.passphraseInput.Text = lxxDeviceInfo.deviceInfo.activateInfo.activateCode;
                        this.lbl_RegisterState.Text = "已激活";
                        this.btnOK.Enabled = false;
                    }));
                }
            }
            catch
            {

            }
        }

        private async void PostAiInfoAsync(string AiCode)
        {
            cmd.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                if (string.IsNullOrEmpty(AiCode)) return;
                //string result = new PosRemoteServices(AppConstVars.sysUser.ccessToken).GetActivateCodeList(AppConstVars.sysUser,AiCode).MessageOrString;
                var resultModel = await SystemApiUtil.GetActivateCodeList(AppConstVars.sysUser, AiCode);
                string result = resultModel.MessageOrString;
                AiCodeGetInfoListModel CurrentAiInfo = new AiCodeGetInfoListModel();
                GetAiCodeInfoListModel AiListInfo = result.JsonToEntity<GetAiCodeInfoListModel>();
                if (AiListInfo != null && AiListInfo.rows != null && AiListInfo.rows.Count > 0)
                {
                    CurrentAiInfo = AiListInfo.rows.Find(p => p.aiCode == AiCode);
                }
                if (CurrentAiInfo != null && !string.IsNullOrEmpty(CurrentAiInfo.aiId))
                {
                    //ReturnModel returnModel = new PosRemoteServices(AppConstVars.sysUser.ccessToken).PostAddActivateCode(AppConstVars.sysUser, AppConstVars.sysStore,CurrentAiInfo);
                    ReturnModel returnModel = await SystemApiUtil.PostAddActivateCode(AppConstVars.sysUser, AppConstVars.sysStore, CurrentAiInfo);
                    if (returnModel.Status != ReturnStatus.Success)
                    {
                        //$"新增Ai激活码失败{CurrentAiInfo.aiCode},{returnModel.MessageOrString}".ShowError();
                        ShowInfoTip($"新增Ai激活码失败{CurrentAiInfo.aiCode},{returnModel.MessageOrString}");
                        return;
                    }

                    GetAiCodeInfoListModel gsData =
                        returnModel.MessageOrString.JsonToEntity<GetAiCodeInfoListModel>();

                    if (gsData.code != 200)
                    {
                        ShowInfoTip($"新增Ai激活码失败{CurrentAiInfo.aiCode},{returnModel.MessageOrString}");
                    }
                    else
                    {
                        ShowInfoTip($"新增Ai激活码成功{CurrentAiInfo.aiCode}，已上传云端！");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowInfoTip($"新增Ai激活码失败{AiCode}！");
            }
            finally
            {
                cmd.HideOpaqueLayer();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void SavePara()
        {
            try
            {
                string sCode = passphraseInput.Text;
                if (sCode.IsNullOrEmpty())
                {
                    MessageBox.Show("选择区域无效，不能保存。");
                    return;
                }
                var paraPartialModel = new ParaPartialModel();
                paraPartialModel.activateCode = passphraseInput.Text;
                AppConstVars.systemsetup.paraPartial = JsonConvert.SerializeObject(paraPartialModel);
                new corecmssystemsetupService().InsertOrUpdate(AppConstVars.systemsetup);
            }
            catch
            {
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                bool isRegister = false;
                string msg = "激活失败。";
                if (checkValue())
                {
                    SetLogInfo("开始激活AI:" + "\r\n");
                    var request = WebRequest.Create(url + "/rpc/device/activate");
                    request.ContentType = "application/json";
                    request.Method = "POST";
                    var payload = new JObject();
                    payload["activateCode"] = this.passphraseInput.Text;

                    var shop = new JObject();
                    shop["code"] = AppConstVars.sysStore.corpId.ToString();
                    shop["name"] = AppConstVars.sysStore.corpId.ToString();
                    payload.Add(new JProperty("shop", shop));

                    using (Stream requestStream = request.GetRequestStream())
                    {
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(payload.ToString());
                        requestStream.Write(buffer, 0, buffer.Length);
                    }
                    var response = (HttpWebResponse)request.GetResponse();

                    string content;
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        content = sr.ReadToEnd();
                    }
                    SetLogInfo("content:" + content + "\r\n");
                    ApiReturnModel apiReturnModel = content.JsonToEntity<ApiReturnModel>();
                    if (apiReturnModel != null && apiReturnModel.data != null && (apiReturnModel.code == 1))
                    {
                        msg = apiReturnModel.msg;
                        LxxDeviceInfoModel lxxDeviceInfo = apiReturnModel.data.ToString().JsonToEntity<LxxDeviceInfoModel>();
                        if (!string.IsNullOrEmpty(lxxDeviceInfo.deviceInfo.activateInfo.activateCode))
                        {
                            this.Invoke(new Action(() =>
                            {
                                this.passphraseInput.Text = lxxDeviceInfo.deviceInfo.activateInfo.activateCode;
                                this.lbl_RegisterState.Text = "已激活";
                                this.btnOK.Enabled = false;
                                isRegister = true;
                            }));
                        }
                    }                    
                }   
                if (!isRegister)
                {
                    MessageBox.Show("激活失败,"+ msg);
                    return;
                }
                SavePara();
                PostAiInfoAsync(passphraseInput.Text);
                MessageBox.Show("激活成功，需要重新启动前台系统");
                Environment.Exit(0);
            }
            catch(Exception ex)
            {
                UIMessageTip.Show(ex.Message);
            }            
        }

        private void frmRegisterCzlAi_Load(object sender, EventArgs e)
        {
            //ai激活码
            if (AppConstVars.systemsetup.paraPartialModel == null)
            {
                AppConstVars.systemsetup.paraPartialModel = new ParaPartialModel();
            }
            passphraseInput.Text = AppConstVars.systemsetup.paraPartialModel.activateCode;

            LoadLxxPara();
        }

        private void LoadLxxPara()
        {
            ShowWaitForm("AI设备初始化中，请稍等...");
            try
            {
                //Task.Factory.StartNew(() =>
                //{
                //    GlobalConstVars.czlAIBusiness.StopProcess();
                //    Thread.Sleep(500);
                //    GlobalConstVars.czlAIBusiness.StartProcess();
                //}).TaskDis();
                //Thread.Sleep(5000);
                Lxx_SetStart();
                //Thread.Sleep(5000);
                Lxx_GetRegister();
                //Thread.Sleep(3000);
                //Lxx_GetCameraImg();
                //Thread.Sleep(1000);
                //Lxx_GetConfig();                
            }
            catch (Exception ex) 
            {
                HideWaitForm();
                MessageBox.Show("错误：" + ex.Message);
            }
            finally
            {
                HideWaitForm();
            }
        }

        
        /// <summary>
        /// 发送AI指令(深圳创智链chuangzhilian)
        /// </summary>
        public void Lxx_GetConfig()
        {
            try
            {
                var request = WebRequest.Create(url + "/config");
                request.Method = "GET";
                var response = (HttpWebResponse)request.GetResponse();
                string content;
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    content = sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                UIMessageTip.Show(ex.Message);
            }     

        }
               

        /// <summary>
        /// 发送AI指令(深圳创智链chuangzhilian)
        /// </summary>
        public void Lxx_GetLogs()
        {
            try
            {
                var request = WebRequest.Create(url + "/logs");
                request.Method = "GET";
                var response = (HttpWebResponse)request.GetResponse();
                string content;
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    content = sr.ReadToEnd();
                }
                rtb_log.Text = content;
            }
            catch (Exception ex)
            {
                UIMessageTip.Show(ex.Message);
            }
        }   

        private bool checkValue()
        {
            string sCode = passphraseInput.Text;
            if (sCode.IsNullOrEmpty())
            {
                MessageBox.Show("AI激活码不能空。");
                return false;
            }
            return true;
        }
                
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 2) {
                Lxx_GetLogs();
            }
        }

        private void btn_GetAiPass_Click(object sender, EventArgs e)
        {
            GsGetAiCodeList productSelect = new GsGetAiCodeList((int)GlobalEnumVars.AiType.Lxx);
            productSelect.TopMost = true;
            if (productSelect.ShowDialog() == DialogResult.Yes)
            {
                if (productSelect.SelectCurrentAiCodeInfo != null)
                {
                    passphraseInput.Text = productSelect.SelectCurrentAiCodeInfo.aiCode;
                    //PostAiInfo(passphraseInput.Text);
                }
            }
        }

        private void passphraseInput_TextChanged(object sender, EventArgs e)
        {
            //SettingModelUtil.settingsModel.aI.CDKEY = passphraseInput.Text;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                GlobalConstVars.lxxAIBusiness.StopProcess();
                Thread.Sleep(500);
                UIMessageBox.Show("停止成功，请退出软件再打开。");
            }).TaskDis();            
        }

        private void btnRangeSet_Click(object sender, EventArgs e)
        {
            string exePath = Application.StartupPath + @"\lxxai\SanQingNiaoCameraSetting.exe";

            try
            {
                // 启动exe程序
                Process.Start(exePath);
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }        
    }
}
